package com.njrsrc.android.tasks;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;

import com.njrsrc.android.bean.UserInfo;
import com.njrsrc.common.utils.Helpers;

public class RegisterTask extends AsyncTask<Object, Integer, Void> {
	private String url;
	private Handler registerHandler;
	private UserInfo registerInfo;
	private Map<String, String> requestMap;

	@Override
	protected Void doInBackground(Object... params) {
		if (params.length < 4) {
			return null;
		}
		registerHandler = (Handler) params[0];
		url = (String) params[1];
		registerInfo = (UserInfo) params[2];
		requestMap = (HashMap<String, String>) params[3];

		String query = "login_name=#&password=#&email=#&name=";
		List<String> postparams = new ArrayList<String>();
		try {
			postparams.add(URLEncoder.encode(requestMap.get("login_name"), "utf-8"));
			postparams.add(requestMap.get("password"));
			postparams.add(URLEncoder.encode(requestMap.get("email"), "utf-8"));
			postparams.add("");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}

		String queryStr = Helpers.combinaStr(query, postparams);

		JSONObject jsonObject = null;
		jsonObject = Helpers.postParams(url, queryStr);
		Message msg = registerHandler.obtainMessage();
		if (jsonObject != null) {
			try {
				if (jsonObject.toString().contains("error_code")) {
					// 返回错误
					registerInfo.setError_code(jsonObject.getString("error_code"));
					registerInfo.setError_message(jsonObject.getString("error_message"));
					msg.what = -2;
				} else {
					registerInfo.setUser_id(jsonObject.getString("user_id"));
					registerInfo.setToken(jsonObject.getString("token"));
					msg.what = 0;
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			
		}else
		{
			msg.what = -2;
		}
		registerHandler.sendMessage(msg);
		return null;
	}
}